package com.kaisu.blog.domain.file;

import cn.hutool.core.io.file.PathUtil;
import com.kaisu.blog.common.exceptions.InternalException;
import com.kaisu.blog.common.util.IdUtils;
import com.kaisu.blog.domain.user.User;
import lombok.Data;

import java.nio.file.Paths;

/**
 * @author kaisu
 */
@Data
public class File {
    /**
     * 文件编号
     */
    private String id;
    /**
     * 文件名称
     */
    private String name;
    /**
     * 预览路径
     */
    private String previewPath;
    /**
     * 文件路径
     */
    private String storagePath;
    /**
     * 文件md5
     */
    private String md5;
    /**
     * 上传用户
     */
    private String uploadUserId;

    public static File create(String name, User uploadUser) {
        File file = new File();
        file.setId(IdUtils.generateId());
        file.setName(name);
        file.setUploadUserId(uploadUser.getId());
        return file;
    }

    public void setStoragePath(String storagePath) {
        if (!PathUtil.exists(Paths.get(storagePath), true)) {
            throw new InternalException("未找到文件路径: " + storagePath);
        }
        this.storagePath = storagePath;
    }

    public String generateFileName() {
        return this.getId() + "-" + this.getName();
    }

}